package org.adream.account.util;

import org.adream.account.service.ADreamServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 使用MD5 来做oauth中state参数的校验
 *
 * @author chenhaoyu
 *
 */
public class StateValidateUtil {
	
	private final static Logger logger = LoggerFactory.getLogger(StateValidateUtil.class);
	
	// 操作类型 是绑定操作 还是 登录操作
	public final static String TYPE_LOGIN = "login";
	
	public final static String TYPE_BIND = "bind";

	public static String getBindState(String uid) {
		return getEncodeState(TYPE_BIND, uid);
	}

	public static String getLoginState(String uid) {
		return getEncodeState(TYPE_LOGIN, uid);
	}

	/**
	 * 
	 * @param type
	 *            操作类型
	 * @param uid
	 * @return MD5(type+uid)_uid
	 */
	private static String getEncodeState(String type, String uid) {

		String code = PasswordUtil.md5Hex(type + uid);

		String state = code + "_" + uid;

		return state;
	}

	/**
	 * @param encodeState
	 * @return
	 * @throws ADreamServiceException
	 */
	public static String getDecodeState(String encodeState) throws ADreamServiceException {

		String md5string = encodeState.split("_")[0];

		String uid = encodeState.split("_")[1];

		if (PasswordUtil.md5Hex(TYPE_BIND + uid).equals(md5string)) {
			return TYPE_BIND + "_" + uid;
		} else if (PasswordUtil.md5Hex(TYPE_LOGIN + uid).equals(md5string)) {
			return TYPE_LOGIN + "_" + uid;
		} else {
			logger.warn("state验证失败，错误的state");
			throw new ADreamServiceException("参数有误");
		}
	}
}